package com.ecommerce.common.exception;

import com.ecommerce.common.core.ApiResult;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ApiResult<Void> handleBusinessException(BusinessException e) {
        log.error("业务异常{},{}",e.getCode(), e.getMessage(), e);
        return ApiResult.fail(e.getCode(), e.getMsg());
    }

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult<Void> handleValidationException(MethodArgumentNotValidException e) {
        log.error("参数验证异常{},{}",e.getStatusCode(), e.getMessage(), e);
        StringBuilder errorMsg = new StringBuilder();
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            errorMsg.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(";");
        }
        return ApiResult.badRequest(errorMsg.toString());
    }

    /**
     * 约束违反异常处理
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ApiResult<Void> handleConstraintViolationException(ConstraintViolationException e) {
        log.error("约束违反异常: {}", e.getMessage(), e);

        StringBuilder errorMsg = new StringBuilder();
        for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
            errorMsg.append(violation.getPropertyPath())
                    .append(": ")
                    .append(violation.getMessage())
                    .append("; ");
        }

        return ApiResult.badRequest(errorMsg.toString());
    }

    /**
     * SQL异常处理
     */
    @ExceptionHandler(SQLException.class)
    public ApiResult<Void> handleSQLException(SQLException e) {
        log.error("数据库异常: {}", e.getMessage(), e);
        return ApiResult.fail("数据库操作失败");
    }

    /**
     * Redis异常处理
     */
    @ExceptionHandler(RedisConnectionFailureException.class)
    public ApiResult<Void> handleRedisException(RedisConnectionFailureException e) {
        log.error("Redis连接异常: {}", e.getMessage(), e);
        return ApiResult.fail("缓存服务异常");
    }

    /**
     * 系统异常处理
     */
    @ExceptionHandler(Exception.class)
    public ApiResult<Void> handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return ApiResult.fail("系统内部错误");
    }
}
